<?php
ini_set("display_errors", "1");
error_reporting(E_ALL);

require_once "../php/dbConnect.php";

// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-validate';

foreach ($_POST as $key => $value) {
$value = urlencode(stripslashes($value));
$req .= "&$key=$value";
}

// post back to PayPal system to validate
$header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
$fp = fsockopen ('ssl://www.paypal.com', 443, $errno, $errstr, 30);

//assign posted variables to local variables
$item_name = $_POST['item_name'];
$item_number = $_POST['item_number'];
$payment_status = $_POST['payment_status'];
$payment_amount = mysql_real_escape_string($_POST['mc_gross']);
$payment_currency = mysql_real_escape_string($_POST['mc_currency']);
$txn_id = mysql_real_escape_string($_POST['txn_id']);
$receiver_email = $_POST['receiver_email'];
$payer_email = $_POST['payer_email'];
$custom = explode('|', $_POST['custom']);

// user input details

$email = mysql_real_escape_string($custom[0]);
$firstName = mysql_real_escape_string($custom[1]);
$lastName = mysql_real_escape_string($custom[2]);
$houseNameNumber = mysql_real_escape_string($custom[3]);
$street = mysql_real_escape_string($custom[4]);
$town = mysql_real_escape_string($custom[5]);
$city = mysql_real_escape_string($custom[6]);
$country = mysql_real_escape_string($custom[7]);
$zipPostCode = mysql_real_escape_string($custom[8]);

if (!$fp) 
{
	// HTTP ERROR
} 
else 
{
	fputs ($fp, $header . $req);
	
	while (!feof($fp)) 
	{
		$res = fgets ($fp, 1024);
	
		if (strcmp ($res, "VERIFIED") == 0) 
		{
			// check the payment_status is Completed
			if($payment_status == "Completed")
			{
				// check that txn_id has not been previously processed
				$txn_id_check = mysql_query("SELECT txn_ID FROM guideOrders WHERE txn_ID = '{$txn_id}'");
				
				if(mysql_num_rows($txn_id_check) != 1)
				{
					// check that receiver_email is your Primary PayPal email
					if($receiver_email == "paypal@moneybug.net")
					{
						// check that payment_amount/payment_currency are correct
						//if((($payment_amount == "0.01")&&($payment_currency == "GBP"))||(($payment_amount == "0.01")&&($payment_currency == "EUR"))||(($payment_amount == "0.01")&&($payment_currency == "USD")))
						if((($payment_amount == "9.99")&&($payment_currency == "GBP"))||(($payment_amount == "11.99")&&($payment_currency == "EUR"))||(($payment_amount == "14.99")&&($payment_currency == "USD")))
						{
							//PROCESS ORDER
							
							$log_query = mysql_query("
								INSERT INTO guideOrders 
									(email,
									firstName,
									lastName,
									houseNameNumber,
									street,
									town,
									city,
									country,
									zipPostCode,
									currency,
									cost,
									txn_ID,
									dateOrdered,
									dispatched)
								VALUES
									('{$email}',
									'{$firstName}',
									'{$lastName}',
									'{$houseNameNumber}',
									'{$street}',
									'{$town}',
									'{$city}',
									'{$country}',
									'{$zipPostCode}',
									'{$payment_currency}',
									'{$payment_amount}',
									'{$txn_id}',
									NOW(),
									'0')
							") or error_log(mysql_error(), 0);
							
							//EMAIL USER WITH CONFIRMATION
							
							$emailTo = $email;
							$emailSubject = "MoneyBug Guide Invoice - {$txn_id}";
							$emailHeaders = array(
								"From: MoneyBug <invoice@moneybug.net>",
								"Content-Type: text/html"
							);
							$emailBody = file_get_contents('confirmPurchaseEmail.php');
							
							//REPLACE EMAIL VARIABLES
							$emailBody = str_replace("{date}", date("D, jS F Y", time()), $emailBody);
							$emailBody = str_replace("{txn_id}", $txn_id, $emailBody);
							$emailBody = str_replace("{name}", stripslashes($firstName)." ".stripslashes($lastName), $emailBody);
							$emailBody = str_replace("{houseNameNumber} {street}", $houseNameNumber. " ".$street, $emailBody);
							$emailBody = str_replace("{town}", $town, $emailBody);
							$emailBody = str_replace("{city}", $city, $emailBody);
							$emailBody = str_replace("{zipPostCode}", $zipPostCode, $emailBody);
							$emailBody = str_replace("{country}", $country, $emailBody);
							
							$emailBody = "<img src='http://www.moneybug.net/images/emailHeader.png' /><div style='font-family:arial;font-size:12px;padding-left:25px'><br /><br />Dear ".stripslashes($firstName)." ".stripslashes($lastName)."<br /><br />".$emailBody;
							mail($emailTo, $emailSubject, $emailBody, implode("\r\n", $emailHeaders));
						}
					}
				}
			}
			
			
			
			
		}	
		else if (strcmp ($res, "INVALID") == 0) 
		{
			// log for manual investigation
		}
	}
	
fclose ($fp);

}
?>